
import { _decorator, Component, Node, NodePool, Prefab , instantiate,} from 'cc';
const { ccclass, property } = _decorator;

interface  IDirctPool
{
    [name:string]:NodePool; //节点
}
interface  IDictPrefab
{
    [name:string]:Prefab;  //存预制资源
}
@ccclass('PoolManager') //节点赤  统一管理节点创建
export class PoolManager  {
 
    public static instance()
    {
        if(!this._instance)
        {
            this._instance=new PoolManager();
        }
        return this._instance;
    }

    private _dictPool:IDirctPool={}
    private  _dictPrefab:IDictPrefab={};
    private static _instance:PoolManager;

    public getNode(prefab:Prefab,parent:Node)  //获取节点上的预制
    {
        let name=prefab.name;
        console.log('get node '+name);
        let node:Node=null;
        this._dictPrefab[name]=prefab;
        const pool =this._dictPool[name];
        if(pool)
        {
            if(pool.size()>0)
            {
                node=pool.get();

            }else
            {
                node=instantiate(prefab);
            }
        }else
        {
            this._dictPool[name]=new NodePool();
            node=instantiate(prefab);
        }
         node.parent=parent;
         node.active=true;
         return node;

        }

    public putNode(node:Node)
    {
        let name=node.name;
        console.log('put node '+name);
        node.parent=null;
        if(!this._dictPrefab[name])
        {
            this._dictPool[name]=new NodePool();
        }
        this._dictPool[name].put(node);
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.0/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.0/manual/en/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.0/manual/en/scripting/life-cycle-callbacks.html
 */
